<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <!--
      Tips: 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮
     -->
    <form action="/" class="search-form">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- /搜索栏 -->

    <!-- 搜索结果 : 搜索了就显示结果框-->
    <search-result v-if="isResultShow" :searchText="searchText" />
    <!-- /历史记录 -->

    <!-- 联想建议: 如果搜索文本不为空显示建议框 -->
    <search-suggestion
      v-else-if="searchText"
      :searchText="searchText"
      @searchFn="onSearch"
    />
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history
      v-else
      :searchHistories="searchHistories"
      @removeHis="removeHisFn"
      @removeAllHis="removeAllHisFn"
      @onSearch="onSearch"
    />
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import SearchHistory from './search-history.vue'
import SearchSuggestion from './search-suggestion.vue'
import SearchResult from './search-result.vue'

import { mapState } from 'vuex'
import { setItem, getItem } from '@/utils/storage.js'

export default {
  name: 'SearchIndex',
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  props: {},
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHistories: getItem('SearchHisKey') || []
    }
  },
  computed: {
    ...mapState(['searchHisKey'])
  },
  watch: {
    searchHistories (val) {
      setItem(this.searchHisKey, val)
    }
  },
  created () {},
  mounted () {},
  methods: {
    onSearch (val) {
      //   console.log(val)
      // 将联想建议面板的数据同步到输入框
      this.searchText = val
      // 加入搜索历史
      // 非重复数据，先进后出
      const ind = this.searchHistories.findIndex(v => v === val)
      if (ind > -1) {
        this.searchHistories.splice(ind, 1)
      }
      this.searchHistories.unshift(val)

      // 显示搜索结果
      this.isResultShow = true
    },
    onCancel () {
      // 取消时路由回退
      this.$router.back()
    },
    removeHisFn (ind) {
      // 删除历史记录
      //   console.log(9)
      this.searchHistories.splice(ind, 1)
    },
    removeAllHisFn () {
      // 删除全部历史记录
      this.searchHistories = []
    }
  }
}
</script>

<style scoped lang="less">
.search-container {
  padding-top: 106px;
  // 将搜索框固定在头部
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
  .van-search__action {
    color: #fff;
  }
}
</style>
